import { 
  NOT_LOADED,
  LOADING_SOURCE_CODE, 
  NOT_BOOTSTRAPPED 
} from '../applications/app.helpers'

export function flattenFnArray(fns) {
  fns = Array.isArray(fns) ? fns: [fns]
  return function(props) {
    return fns.reduce((p, fn) => p.then(() => fn(props)), Promise.resolve())
  }
}

export async function toLoadPromise(app) {
  if (app.loadPromise) {
    return app.loadPromise
  }
  if (app.status !== NOT_LOADED && app.status !== LOAD_ERROR) {
    return app
  }

  app.status = LOADING_SOURCE_CODE

  return (app.loadPromise = Promise.resolve()
    .then(() => {
      const loadPromise = app.loadApp(app.customProps)
      return loadPromise.then(val => {
        app.loadErrorTime = null
        app.status = NOT_BOOTSTRAPPED // 表示还没启动
        // 将多个 promise 组合一起
        app.bootstrap = flattenFnArray(val.bootstrap)
        app.mount = flattenFnArray(val.mount)
        app.unmount = flattenFnArray(val.unmount)
        delete app.loadPromise
        return app
      })
    })
  )
}